<template>
  <NUpload style="width: 240rem" :custom-request="(e: any) => commonUpload(e)" :default-file-list="imgList"
    :accept="props.typeAccept" :on-remove="handleRemove" :max="props.max">
    <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost :disabled="props.disabled">上传文件</NButton>
  </NUpload>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import { NButton, NUpload, useMessage } from 'naive-ui'
import type { UploadCustomRequestOptions } from 'naive-ui'
import { sendRequest } from '@/utils/api'

const message = useMessage()
const emits = defineEmits(['getList'])
const props = defineProps({
  fileList: { type: Array, default: () => [] },
  max: { type: Number, default: () => 100000 },
  typeOnlyText: { type: String, default: () => '支持所有格式上传' },
  typeAccept: { type: String, default: () => 'multiple' },
  disabled: { type: Boolean, default: () => false }
})

//添加附件
const imgHZ = ['jpg', 'png', 'jpeg']
const imgList = ref<any>([])
const tasmpList = ref<any>([])
const commonUpload = async ({
  file,
  onFinish,
  onError,
  onProgress
}: UploadCustomRequestOptions) => {
  const tmp = file.name.split('.')
  if (!imgHZ.includes(tmp[tmp.length - 1]) && props.typeAccept != 'multiple') return message.error('请上传图片类型'), onError()
  const fileData = new FormData()
  fileData.append('file', file.file as File)
  const [error, res] = await sendRequest({
    module: 'upload',
    api: 'uploadFile',
    override: {
      data: fileData,
      onUploadProgress(v: any) {
        onProgress({ percent: Math.ceil(v.progress) })
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error('上传失败'), onError()
  tasmpList.value.push({
    id: res.data.fileId,
    name: res.data.name,
    status: 'finished',
    url: res.data.url
  })
  message.success('上传成功')
  returnPictures()
  onFinish()
}
// 删除
const handleRemove = ({ file }: any) => {
  const index = tasmpList.value.findIndex((it: any) => it.name == file.name)
  tasmpList.value.splice(index, 1)
  message.success('删除成功')
  returnPictures()
  return true
}
// 处理图片
function returnPictures() {
  emits('getList', tasmpList.value.map((it: any) => it.id).join(','))
}

watchEffect(() => {
  if (imgList.value.length && !props.fileList?.length) {
    return (
      imgList.value.splice(0, imgList.value.length),
      tasmpList.value.splice(0, tasmpList.value.length)
    )
  }
  if (imgList.value.length || !props.fileList?.length) return
  props.fileList.map((it: any) => {
    imgList.value.push({
      id: it.id,
      name: it.name,
      status: 'finished',
      url: it.path
    })
    tasmpList.value.push({
      id: it.id,
      name: it.name,
      status: 'finished',
      url: it.path
    })
  })
})
</script>
